﻿#if UNITY_EDITOR

using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;

namespace UFrame
{
    /// <summary>
    /// 负责输出资源version.txt ,resList.txt
    /// 
    /// </summary>
    public class ABTools
    {
        public static List<string> pathList = new List<string>
        {
            "bawAsset/Effect",
            //"3rdParty/UFrameCode/Xlua",
            "bawAsset/Xlua",
            "bawAsset/Scene",
            "bawAsset/CSV",
            //"bawAsset/Font",
            "bawAsset/Prefabs",
        };

        /// <summary>
        /// 选择AB包名字
        /// </summary>
        public static List<string> alonePathList = new List<string>
        {
            "bawAsset/Xlua",
        };


        [MenuItem("Plateface/AB/build AB", false, 1)]
        public static void BuildAB()
        {
            SetAssetBundlesName();
            CreateResListTXT();
            BuildPipeline.BuildAssetBundles(ABPath.GetPath(), BuildAssetBundleOptions.UncompressedAssetBundle,
                BuildTarget.StandaloneWindows);

            ABVersion.BuildVersion();
            AssetDatabase.Refresh();
        }


        [MenuItem("Plateface/AB/build Select AB", false, 2)]
        public static void BuildSelectAB()
        {
            List<AssetBundleBuild> aList = new List<AssetBundleBuild>();
            List<string> abNameList = new List<string>();
            foreach (var name in alonePathList)
            {
                string path = Path.Combine(Application.dataPath, name);
                string abName = name.Substring(name.LastIndexOf("/") + 1);
                abNameList.Add(abName);

                var assetNameList = Pack(path);
                AssetBundleBuild ab = new AssetBundleBuild();
                ab.assetBundleName = abName;
                ab.assetNames = assetNameList.ToArray();
                aList.Add(ab);
            }

            if (aList.Count == 0)
            {
                Debug.LogError("build AB count 0");
                return;
            }

            CreateResListTXT();

            BuildPipeline.BuildAssetBundles(ABPath.GetPath(), aList.ToArray(),
                BuildAssetBundleOptions.UncompressedAssetBundle, BuildTarget.StandaloneWindows);

            ABVersion.BuildVersion(abNameList);
            AssetDatabase.Refresh();
        }

        [MenuItem("Plateface/AB/ClearAssetBundlesName", false, 100)]
        public static void ClearAssetBundlesName()
        {
            int length = AssetDatabase.GetAllAssetBundleNames().Length;
            string[] oldAssetBundleNames = new string[length];
            for (int i = 0; i < length; i++)
            {
                oldAssetBundleNames[i] = AssetDatabase.GetAllAssetBundleNames()[i];
            }

            for (int j = 0; j < oldAssetBundleNames.Length; j++)
            {
                AssetDatabase.RemoveAssetBundleName(oldAssetBundleNames[j], true);
            }
        }

        [MenuItem("Plateface/AB/SetAssetBundlesName", false, 101)]
        public static void SetAssetBundlesName()
        {
            foreach (var name in pathList)
            {
                string path = Path.Combine(Application.dataPath, name);
                string abName = name.Substring(name.LastIndexOf("/") + 1);
                SetAssetBundleName(path, abName);
            }
            AssetDatabase.Refresh();
        }

        [MenuItem("Plateface/AB/BuildABVersionTXT", false, 103)]
        public static void BuildABVersion()
        {
            ABVersion.BuildVersion();
        }


        /// <summary>
        /// 设置AssetBundleName
        /// </summary>
        /// <param name="fullpath">文件夹路径</param>
        private static void SetAssetBundleName(string fullPath, string abName)
        {
            string[] files = Directory.GetFiles(fullPath, "*.*", SearchOption.AllDirectories);
            if (files == null || files.Length == 0)
            {
                return;
            }

            foreach (string file in files)
            {
                if (file.EndsWith(".meta") || file.EndsWith(".DS_Store"))
                {
                    continue;
                }

                string s = file.Substring(Application.dataPath.Length);

                AssetImporter importer = AssetImporter.GetAtPath("Assets" + s);
                if (importer != null)
                {
                    importer.assetBundleName = abName;
                }
                else
                {
                    Debug.LogFormat("Set AssetName Fail, File:{0}, Msg:Importer is null", file);
                }
            }
        }

        private static void CreateResListTXT()
        {
            StringBuilder resSB = new StringBuilder();
            foreach (var name in pathList)
            {
                string path = Path.Combine(Application.dataPath, name);
                string abName = name.Substring(name.LastIndexOf("/") + 1);
                string[] files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);

                if (files == null || files.Length == 0)
                {
                    continue;
                }

                foreach (string file in files)
                {
                    if (file.EndsWith(".meta") || file.EndsWith(".DS_Store"))
                    {
                        continue;
                    }

                    string s = file.Substring(Application.dataPath.Length);
                    string assetPath = "Assets" + s;
                    resSB.AppendLine(abName + "|" + assetPath);
                }
            }

            //输出资源文件
            ABVersion.WriteTXT("resList.txt", resSB.ToString());
        }

        private static List<string> Pack(string path)
        {
            List<string> assetNameList = new List<string>();
            DirectoryInfo folder = new DirectoryInfo(path);
            FileSystemInfo[] files = folder.GetFileSystemInfos();
            int length = files.Length;
            for (int i = 0; i < length; i++)
            {
                if (files[i] is DirectoryInfo)
                {
                    Pack(files[i].FullName);
                }
                else
                {
                    if (!files[i].Name.EndsWith(".meta"))
                    {
                        string assetPath = files[i].FullName.Substring(Application.dataPath.Length);
                        assetNameList.Add("Assets" + assetPath);
                    }
                }
            }

            return assetNameList;
        }
    }
}
#endif